import 'package:flutter/cupertino.dart';
import 'package:hitutor/Util/Global.dart';
import 'package:hitutor/Util/HttpGo.dart';
import 'package:hitutor/Util/MyColor.dart';
import 'package:hitutor/Util/PageUtil.dart';
import 'package:hitutor/Widget/MyDialog.dart';
import 'package:hitutor/Widget/MyImage.dart';
import 'package:hitutor/Widget/MyInput.dart';
import 'package:hitutor/Widget/MyPage.dart';

import 'FriendSearch.dart';

class FriendList extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _FriendList();
  }
}

class _FriendList extends State<FriendList> {
  TextEditingController controller = TextEditingController();

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      getFriList();
      getInviteFriList();
    });
    super.initState();
  }

  List<dynamic> friList = [];

  getFriList() {
    HttpGo(context).get("/Profile/GetRelationshipList?studentId=${Global.studentId}", {}, (data) {
      friList = data["relationshipList"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  DelFri(int index) {
    showBtn2Dialog(context, "您確認要刪除該好友嗎", "取消", () {}, "確認", () {
      HttpGo(context).post("/Profile/DeleteRelationship", {
        "studentId": Global.studentId,
        "relatedUserId": friList[index]["userId"],
      }, (data) {
        friList.removeAt(index);
        setState(() {});
      }, (code, error) => showToast(error));
    });
  }

  List<dynamic> inviteList = [];

  getInviteFriList() {
    HttpGo(context).get("/Profile/GetInviteRelationshipList?studentId=${Global.studentId}", {}, (data) {
      inviteList = data["relationshipList"];
      setState(() {});
    }, (code, error) => showToast(error));
  }

  DisagreeInvite(int index) {
    showBtn2Dialog(context, "您確認要拒絕此交友邀請", "取消", () {}, "確認", () {
      HttpGo(context).post("/Profile/DeleteRelationship", {
        "studentId": Global.studentId,
        "relatedUserId": inviteList[index]["userId"],
      }, (data) {
        inviteList.removeAt(index);
        setState(() {});
      }, (code, error) => showToast(error));
    });
  }

  AgreeInvite(int index) {
    showBtn2Dialog(context, "您確認要同意此交友邀請", "取消", () {}, "確認", () {
      HttpGo(context).post("/Profile/AcceptRelationship", {
        "studentId": Global.studentId,
        "relatedUserId": inviteList[index]["userId"],
      }, (data) {
        friList.add(inviteList[index]);
        inviteList.removeAt(index);
        setState(() {});
      }, (code, error) => showToast(error));
    });
  }

  searchUser(String userId) {
    if (userId.isEmpty) return;
    PageUtil().open(context, FriendSearch(searchKey: userId));
  }

  @override
  Widget build(BuildContext context) {
    return MyPage(
        "朋友圈",
        SingleChildScrollView(
            child: Container(
                padding: EdgeInsets.all(16),
                child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
                  Container(
                      decoration: Global.getBg(MyColor.F2, 5),
                      padding: EdgeInsets.fromLTRB(4, 0, 8, 0),
                      margin: EdgeInsets.fromLTRB(0, 8, 0, 8),
                      height: 28,
                      child: Row(children: [
                        Expanded(
                            child: NormalInput(
                                hintText: "User ID",
                                controller: controller,
                                fontSize: 12,
                                inputType: NormalInput.Number,
                                onSubmit: searchUser)),
                        LocalImage("search_blue.png", width: 16, onTap: () {
                          searchUser(controller.text);
                        })
                      ])),
                  Container(
                      margin: EdgeInsets.fromLTRB(0, 16, 0, 8),
                      child: Text("好友列表", style: TextStyle(fontSize: 16, color: MyColor.C99, fontWeight: FontWeight.bold))),
                  ListView.builder(
                      itemCount: friList.length,
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return ItemFriend(friList[index], showDelete: true, onDeleteTap: () {
                          DelFri(index);
                        });
                      }),
                  Container(height: 1, color: MyColor.EE, margin: EdgeInsets.only(top: 8)),
                  Container(
                      margin: EdgeInsets.fromLTRB(0, 16, 0, 8),
                      child: Text("交友邀請", style: TextStyle(fontSize: 16, color: MyColor.C99, fontWeight: FontWeight.bold))),
                  ListView.builder(
                      itemCount: inviteList.length,
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return ItemFriend(inviteList[index], showAgree: true, showDelete: true, onAgreeTap: () {
                          AgreeInvite(index);
                        }, onDeleteTap: () {
                          DisagreeInvite(index);
                        });
                      })
                ]))));
  }
}

class ItemFriend extends StatelessWidget {
  bool showInvite = false;
  bool showAgree = false;
  bool showDelete = false;
  Function()? onInviteTap;
  Function()? onAgreeTap;
  Function()? onDeleteTap;

  dynamic friendInfo;

  ItemFriend(this.friendInfo, {showInvite, showAgree, showDelete, this.onInviteTap, this.onAgreeTap, this.onDeleteTap}) {
    this.showInvite = showInvite ?? false;
    this.showAgree = showAgree ?? false;
    this.showDelete = showDelete ?? false;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        height: 32,
        padding: EdgeInsets.only(left: 12),
        child: Row(children: [
          Container(
              width: 80,
              child: Text("${friendInfo["userId"]}", style: TextStyle(fontSize: 12, color: MyColor.C99, fontWeight: FontWeight.bold))),
          Expanded(child: Text("${friendInfo["name"]}", style: TextStyle(fontSize: 12, color: MyColor.C99, fontWeight: FontWeight.bold))),
          Visibility(visible: showInvite, child: LocalImage("user-add.png", width: 20, padding: EdgeInsets.all(6), onTap: onInviteTap)),
          Visibility(visible: showAgree, child: LocalImage("check-circle.png", width: 20, padding: EdgeInsets.all(6), onTap: onAgreeTap)),
          Visibility(visible: showDelete, child: LocalImage("cross-circle.png", width: 20, padding: EdgeInsets.all(6), onTap: onDeleteTap)),
        ]));
  }
}
